<?php

/**
 * This is the model class for table "{{user_profile}}".
 *
 * The followings are the available columns in table '{{user_profile}}':
 * @property integer $ID
 * @property integer $userID
 * @property string $fullname
 * @property string $gender
 * @property integer $dateofbirth
 * @property string $phone
 * @property string $email
 * @property string $school
 * @property string $city
 * @property integer $avatar
 */
class UserProfile extends CActiveRecord
{
  public $captcha;
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return UserProfile the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{user_profile}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
		array('fullname, email', 'required','on'=>'register,create'),
		array('email', 'required','on'=>'forgot'),
		array('email','email'),
		array('email','validateEmail','on'=>'register,create'),
		array('email','validateEmailForgot','on'=>'forgot'),
		//array('avatar','ext.Validate.MyFileValidator','allowEmpty'=>true,'types'=>'jpg,jpeg,png,gif',),
		array('avatar','file','allowEmpty'=>true,'types'=>'jpg,jpeg,png,gif',),
		array('userID, avatar', 'numerical', 'integerOnly'=>true),
		array('fullname, school, city', 'length', 'max'=>255),
		array('gender', 'length', 'max'=>1),
		array('phone', 'length', 'max'=>20),
		array('email', 'length', 'max'=>100),
		array('captcha','required','on'=>'register'),
		array('captcha','captcha', 'allowEmpty'=>!CCaptcha::checkRequirements(),'on'=>'register'),
		// The following rule is used by search().
		// Please remove those attributes that should not be searched.
		array('ID, userID, fullname, gender, dateofbirth, phone, email, school, city, avatar', 'safe', 'on'=>'search'),
		);
	}
 /**
   * Check email if duplicate
   */
	public function validateEmail($att, $param) {
	  $this->email = strtolower(trim($this->email));
	  $email = UserProfile::model()->find(array('condition'=>'LCASE(`email`)=:email','params'=>array(':email'=>$this->email)));
	  if(!empty($email)) {
	    $this->addError('email', 'Địa chỉ email này đã tồn tại');
	    return false;
	  }
	  return true;
	}
  /**
   * Check email exist? actived? deleted?
   */
	public function validateEmailForgot($att,$param) {
	  $this->email = strtolower(trim($this->email));
	  if(filter_var($this->email, FILTER_VALIDATE_EMAIL)) {
  	  $exist = Yii::app()->db->createCommand()
  	        ->select('up.email,u.active,u.deleted')
  	        ->from('tbl_user_profile as up')
  	        ->join('tbl_user as u','u.ID=up.userID')
  	        ->where('LCASE(up.email)="'.$this->email.'"')
  	        ->queryRow();
  	  
	    if(empty($exist)) {
        $this->addError('email', 'Địa chỉ email không hợp lệ');
        return false;
	    }
	    elseif($exist['active']==0) {
	      $this->addError('email', 'Tài khoản của bạn chưa được kích hoạt');
	      return false;
	    }
	    elseif($exist['deleted']==1) {
	      $this->addError('email', 'Tài khoản của bạn đã bị xóa khỏi hệ thống');
	      return false;
	    }
	    else {
	      return true;
	    }
	  }
    return true;
	}
	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'ID' => 'ID',
			'userID' => 'User',
			'fullname' => 'Họ và tên',
			'gender' => 'Giới tính',
			'dateofbirth' => 'Ngày sinh',
			'phone' => 'Điện thoại',
			'email' => 'Email',
			'school' => 'Trường',
			'city' => 'Tỉnh/Thành phố',
			'avatar' => 'Hình đại diện',
		  'captcha'=> 'Mã xác nhận'
		);
	}
  
	public function getCity() {
	  //Tam thoi gan mang cung, sau nay them tbl_city
	  $array = array();
	  $array['hcm'] = 'Hồ Chí Minh';
	  $array['bt'] = 'Bến Tre';
	  $array['dn'] = 'Đồng Nai';
	  $array['la'] = 'Long An';
	  return $array;
	}
	
	/**
	 * return avatar of user
	 * @author K.D
	 */
  public function getAvatar($userID) {
    $avatar = "";
    $profile = UserProfile::model()->findByAttributes(array('userID'=>$userID));
    if(!empty($profile) && $profile->avatar!==null) {
      $file = File::model()->findByPk($profile->avatar);
      if(!empty($file) && file_exists(Yii::app()->basePath.'/../upload/avatar/thumbs_70x70/'.$file->filesaved)) {
        $avatar = $file->filesaved;
      }
    }
    return $avatar;
  }	
  
  /**
   * get gender of user
   * @author K.D
   */
  public function getGender() {
    if($this->gender==1)
      return 'Nam';
    else
      return 'Nữ';
  }
  
	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('ID',$this->ID);
		$criteria->compare('userID',$this->userID);
		$criteria->compare('fullname',$this->fullname,true);
		$criteria->compare('gender',$this->gender,true);
		$criteria->compare('dateofbirth',$this->dateofbirth);
		$criteria->compare('phone',$this->phone,true);
		$criteria->compare('email',$this->email,true);
		$criteria->compare('school',$this->school,true);
		$criteria->compare('city',$this->city,true);
		$criteria->compare('avatar',$this->avatar);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
}